package com.smsc.headend.task.engine.handler.impl.ansi;

import cn.hutool.json.JSONUtil;
import com.smsc.headend.common.enums.errorcode.TaskHandlerErrorCode;
import com.smsc.headend.module.data.enums.OperationName;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.protocol.ansi.AnsiByteBuffer;
import com.smsc.headend.module.protocol.ansi.AnsiData;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.AtomicTaskState;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import com.smsc.headend.task.engine.po.TouItem;
import com.smsc.headend.task.engine.utils.AnsiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@Slf4j
public class GetTouWeekHandler implements TaskHandler {
    public static final String SUB_TASK_COMPLETED = "subTaskCompleted";
    @Autowired
    TaskDAO taskDAO;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData deviceData, String actionResult) throws UDISTaskHandlerException {
        OperationName operationName = OperationName.forId(atomicTask.getOperationId());
        if (!(deviceData instanceof AnsiData)) {
            log.error("result={}, data={}", actionResult, deviceData);
            throw new UDISTaskHandlerException(TaskHandlerErrorCode.DEVICE_DATA_TYPE_NOT_SUPPORT.toString());
        }
        AnsiData ansiData = (AnsiData) deviceData;
        log.info("Get Tou Week {}", ansiData.getAnsiByteBuffer());
        AnsiByteBuffer dataBuffer = ansiData.getAnsiByteBuffer();
        Map<Integer, List<TouItem>> weeks = AnsiUtil.parseTouWeek(dataBuffer);
        log.info("Get Tou Week执行结果: {}", JSONUtil.toJsonStr(weeks));
        taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), operationName.getName(), weeks, 600L, true);

        AtomicTaskState atomicTaskState = taskDAO.hashGetAtomicTaskState(atomicTask.getAtomicTaskNo());

        // 执行四次
        if (atomicTaskState.getBlockNumber() == 3) {
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), SUB_TASK_COMPLETED, true,600L, true);
            return 1;
        }

        atomicTaskState.setBlockNumber(atomicTaskState.getBlockNumber() + 1);
        taskDAO.hashSetAtomicTaskState(atomicTask.getAtomicTaskNo(), task, atomicTaskState.getRetryTimes(), atomicTaskState);

        return 0;
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error msg:{}", message);
        taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), "Handle Get Tou Week", message, 3600l, false);
        return -1;
    }

}

